package me.yiyou.meihua.utils

import android.icu.util.ChineseCalendar
import me.yiyou.meihua.data.LunarDate

/**
 * 获取农历年月日时的方法
 * 需要api 26+
 * 返回一个LunarDate对象
 */
fun getYMDHmethod(): LunarDate {
    // 解析农历日期
    val lunarYear = getYearByDiZhi() // 农历年
    val lunarMonth = getMonth() // 农历月
    val lunarDay = getDay() // 农历日
    val lunarHour = getHour() // 农历时辰

    LogUtil.e("lunarYear:$lunarYear,lunarMonth:$lunarMonth,lunarDay:$lunarDay,lunarHour:$lunarHour")
    return LunarDate(year=lunarYear, month = lunarMonth, day = lunarDay, hour = lunarHour)    // 创建数据类，返回对象
}

/**
 * 获取当前年份数,地支数年份
 */
fun getYearByDiZhi(): Int {
    val chineseCalendar = ChineseCalendar().apply {
        timeInMillis = System.currentTimeMillis()
    }
    // 解析农历日期
    val lunarYear = chineseCalendar.get(ChineseCalendar.YEAR)
    // 处理时间, 起卦用地支数,年对12取余,0+1
    if (lunarYear % 12 == 0) {
        return 1
    } else {
        return lunarYear % 12
    }
}

/**
 * 获取当前农历月份
 */
fun getMonth(): Int {
    val chineseCalendar = ChineseCalendar().apply {
        timeInMillis = System.currentTimeMillis()
    }
    return chineseCalendar.get(ChineseCalendar.MONTH) + 1 // 月份（需+1）
}

/**
 * 获取当前农历日
 */
fun getDay(): Int {
    val chineseCalendar = ChineseCalendar().apply {
        timeInMillis = System.currentTimeMillis()
    }
    return chineseCalendar.get(ChineseCalendar.DAY_OF_MONTH)
}

/**
 * 获取时辰数
 */
fun getHour(): Int {
    val chineseCalendar = ChineseCalendar().apply {
        timeInMillis = System.currentTimeMillis()
    }
    val lunarHour = chineseCalendar.get(ChineseCalendar.HOUR_OF_DAY)
    return when (lunarHour) {
        23, 24, 0 -> 1
        1, 2 -> 2
        3, 4 -> 3
        5, 6 -> 4
        7, 8 -> 5
        9, 10 -> 6
        11, 12 -> 7
        13, 14 -> 8
        15, 16 -> 9
        17, 18 -> 10
        19, 20 -> 11
        21, 22 -> 12
        else -> 0
    }
}